/**
 *   This file is part of Java Simple Sampler.
 *
 *   Java Simple Sampler is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License.
 *
 *   Java Simple Sampler is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with Java Simple Sampler.  If not, see <http://www.gnu.org/licenses/>.
 *
 *   @author David Lapetina	
 */
package net.onirik.mao.sampler.midi;

import java.util.ArrayList;
import java.util.List;

import javax.sound.midi.InvalidMidiDataException;
import javax.sound.midi.MidiDevice;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.MidiUnavailableException;
import javax.sound.midi.Receiver;
import javax.sound.midi.Sequence;
import javax.sound.midi.Sequencer;

public class MidiHelper {

	private final MidiDevice device;
	
	private final Sequencer seqr;

	private Sequence seq;
	
	private MidiHelper(MidiDevice.Info info) throws MidiUnavailableException, InvalidMidiDataException {
		device = getMidiDevice(info);
		seqr = MidiSystem.getSequencer();
		seq = SequenceGeneration.GenSeq();
	}
/*
	public void registerReceiver(Receiver receiver)
			throws MidiUnavailableException {
		device.getTransmitter().setReceiver(receiver);
	}
*/
	public void registerReceiver(Receiver receiver)
			throws MidiUnavailableException {
		seqr.getTransmitter().setReceiver(receiver);
	}
	
	private MidiDevice getMidiDevice(MidiDevice.Info info)
			throws MidiUnavailableException {
		MidiDevice device = MidiSystem.getMidiDevice(info);
		return device;
	}

	public static List listDevices(String name) throws MidiUnavailableException {
		MidiDevice.Info[] info = MidiSystem.getMidiDeviceInfo();
		List devices = new ArrayList();
		for (int i = 0; i < info.length; i++) {
			if (name == null || info[i].getName().indexOf(name) > -1) {
				//System.out.println("Added :");
				//System.out.println(i + ") " + info[i]);
				//System.out.println("Name: " + info[i].getName());
				//System.out.println("Description: " + info[i].getDescription());
				devices.add(info[i]);
			}
		}
		return devices;
	}

	public static MidiHelper getMidiHelper(MidiDevice.Info info)
			throws MidiUnavailableException, InvalidMidiDataException {
		return new MidiHelper(info);
	}

	public void open() throws MidiUnavailableException, InvalidMidiDataException {
		if (device.isOpen())
			return;
		device.open();
		
		if (seqr.isOpen())
			return;
		seqr.open();
		seqr.setSequence(seq);
		seqr.setTempoInBPM(180);
		seqr.start();
		
	}

	public void close() {
		if (device.isOpen())
			device.close();
		
		if (seqr.isOpen())
			seqr.close();
	}
}
